<template>
  <el-card class="form-container" shadow="never">
    <el-form
      :model="productCate"
      :rules="rules"
      ref="productCateFrom"
      label-width="150px"
    >
      <el-form-item label="分类名称：" prop="name">
        <el-input @change="handleChange" v-model="productCate.name"></el-input>
      </el-form-item>
      <el-form-item label="上级分类：">
        <el-select v-model="productCate.parentId" placeholder="请选择分类">
          <el-option
            v-for="item in selectProductCateList"
            :key="item.id"
            :label="item.shopTypeName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('productCateFrom')"
          >提交</el-button
        >
        <el-button v-if="!isEdit" @click="resetForm('productCateFrom')"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import {
  getShopType,
  addShopType,
  getShopTypeById,
  updateShopTypeById,
} from "../../../../api/productAttrCate";

const defaultProductCate = {
  description: "",
  icon: "",
  keywords: "",
  name: "",
  navStatus: 0,
  parentId: 0,
  productUnit: "",
  showStatus: 0,
  sort: 0,
  productAttributeIdList: [],
};
export default {
  name: "ProductCateDetail",
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      shopTypeId: 0,
      FilterProperties: "",
      optionProps: {
        value: "id",
        label: "name",
        children: "child",
      },
      username: "",
      productCate: Object.assign({}, defaultProductCate),
      selectProductCateList: [],
      rules: {
        name: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          {
            min: 2,
            max: 140,
            message: "长度在 2 到 140 个字符",
            trigger: "blur",
          },
        ],
      },
      filterAttrs: [],
      filterProductAttrList: [
        {
          value: [],
        },
      ],
    };
  },
  created() {
    if (this.isEdit) {
      if (this.$route.query.id != null) {
        this.shopTypeId = this.$route.query.id;
        getShopTypeById(this.shopTypeId).then(({ data }) => {
          var res = data.data;
          this.productCate = Object.assign({}, defaultProductCate);
          console.log(this.productCate);
          this.productCate.name = res.shopTypeName;
          // this.ptoductCate.SuperiorShopTypeId = res.superiorShopTypeId;
          if (res.superiorShopTypeId !== 0) {
            getShopTypeById(res.superiorShopTypeId).then((response) => {
              // console.log(response);
              var shopTypeName = response.data.data.shopTypeName;
              var shopTypeId = response.data.data.id;
              // console.log(shopTypeName);

              this.selectProductCateList.unshift({
                id: 0,
                shopTypeName: "无上级分类",
              });

              this.selectProductCateList.unshift({
                id: shopTypeId,
                shopTypeName: shopTypeName,
              });

              getShopType().then(({ data }) => {
                console.log(this.selectProductCateList);
                data.data.forEach((element) => {
                  if (
                    this.selectProductCateList[0].id !== element.id &&
                    element.id !== parseInt(this.$route.query.id)
                  ) {
                    this.selectProductCateList.push(element);
                  }
                });
              });
            });
          } else {
            getShopType().then(({ data }) => {
              data.data.forEach((element) => {
                if (element.id !== parseInt(this.$route.query.id)) {
                  this.selectProductCateList.push(element);
                }
              });

              this.selectProductCateList.unshift({
                id: 0,
                shopTypeName: "无上级分类",
              });
            });
          }
        });
      } else {
        this.shopTypeId = 0;
      }

      this.filterProductAttrList = [];
    } else {
      this.productCate = Object.assign({}, defaultProductCate);
    }
    this.getSelectProductCateList();
    this.getProductAttrCateList();
  },
  methods: {
    handleChange(value) {
      console.log(value);
    },
    getSelectProductCateList() {
      if (!this.isEdit) {
        getShopType().then(({ data }) => {
          this.selectProductCateList = data.data;
          this.selectProductCateList.unshift({
            id: 0,
            shopTypeName: "无上级分类",
          });
        });
      }
    },
    getProductAttrCateList() {
      // fetchListWithAttr().then(response => {
      let list = [];
      for (let i = 0; i < list.length; i++) {
        let productAttrCate = list[i];
        let children = [];
        if (
          productAttrCate.productAttributeList != null &&
          productAttrCate.productAttributeList.length > 0
        ) {
          for (
            let j = 0;
            j < productAttrCate.productAttributeList.length;
            j++
          ) {
            children.push({
              label: productAttrCate.productAttributeList[j].name,
              value: productAttrCate.productAttributeList[j].id,
            });
          }
        }
      }
      this.filterAttrs.push();
      // });
    },
    getProductAttributeIdList() {
      //获取选中的筛选商品属性
      let productAttributeIdList = [];
      for (let i = 0; i < this.filterProductAttrList.length; i++) {
        let item = this.filterProductAttrList[i];
        console.log(item);
        if (item.value !== null && item.value.length === 2) {
          productAttributeIdList.push(item.value[1]);
        }
      }
      return productAttributeIdList;
    },
    onSubmit(formName) {
      // console.log(this.rules);
      // console.log(this.productCate);
      this.$refs[formName].validate((valid) => {
        // console.log(this.productCate);
        // console.log(valid);
        if (valid) {
          this.$confirm("是否提交数据", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            if (this.isEdit) {
              this.productCate.productAttributeIdList = this.getProductAttributeIdList();
              var editRes = {
                ShopTypeName: this.productCate.name,
                SuperiorShopTypeId: this.productCate.parentId,
                Measure: "",
                ShopTypeIconId: 0,
                FilterProperties: "",
                keyword: "",
              };
              console.log(editRes);
              // console.log(this.$route.query.id);
              updateShopTypeById(parseInt(this.$route.query.id), editRes).then(
                () => {
                  this.$message({
                    message: "修改成功",
                    type: "success",
                    duration: 1000,
                  });
                  this.$router.back();
                }
              );
              // updateProductCate(this.$route.query.id, this.productCate).then(
              // (response) => {
              //   console.log(response);

              // }
              // );
            } else {
              this.productCate.productAttributeIdList = this.getProductAttributeIdList();
              var res = {
                ShopTypeName: this.productCate.name,
                SuperiorShopTypeId: this.productCate.parentId,
                Measure: "",
                ShopTypeIconId: 0,
                FilterProperties: "",
                keyword: "",
              };
              console.log(res);
              addShopType(res).then(({ data }) => {
                console.log(data);
                this.$refs[formName].resetFields();
                this.resetForm(formName);
                this.$message({
                  message: "提交成功",
                  type: "success",
                  duration: 1000,
                });
                this.$router.back();
              });
            }
          });
        } else {
          this.$message({
            message: "验证失败",
            type: "error",
            duration: 1000,
          });
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.productCate = Object.assign({}, defaultProductCate);
      this.getSelectProductCateList();
      this.filterProductAttrList = [
        {
          value: [],
        },
      ];
    },
    removeFilterAttr(productAttributeId) {
      if (this.filterProductAttrList.length === 1) {
        this.$message({
          message: "至少要留一个",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      var index = this.filterProductAttrList.indexOf(productAttributeId);
      if (index !== -1) {
        this.filterProductAttrList.splice(index, 1);
      }
    },
    handleAddFilterAttr() {
      if (this.filterProductAttrList.length === 3) {
        this.$message({
          message: "最多添加三个",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      this.filterProductAttrList.push({
        value: null,
        key: Date.now(),
      });
    },
  },
  filters: {
    filterLabelFilter(index) {
      if (index === 0) {
        return "筛选属性：";
      } else {
        return "";
      }
    },
  },
};
</script>

<style scoped></style>
